import './style.css'
import { Button, Input, Popconfirm, Table, Timeline } from 'antd'
import { commonInputProps } from '@/views/ShoppingCart/commonProps.ts'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
  createOrderItem,
  getAreaDetail,
  getOrderLog,
  getShoppingOrderInfo,
  getShoppingOrderItems,
  getSpecs,
  getSpecVals,
  pauseTheOrderItem
} from '@/api/shoppingCart.ts'
import { getUrlSearchParams, hsHandleTableDateTime, initPageType, message, usePageChange } from '@hs-admin/utils'
import { getStateLabel } from './OrderList.tsx'
import DataBaseInfoModal from '@/views/ShoppingCart/components/DataBaseInfoModal.tsx'
import { getTimeLabel } from '@/views/ShoppingCart/SubmitShoppingOrder.tsx'
import ItemModal from '@/views/ShoppingCart/components/ItemModal.tsx'
import { localShoppingData } from '@/views/ShoppingCart/LocalShoppingData.ts'
import { getProjectInfor } from '@/api/developCenter/project.ts'
import { HsAdminDataItemDetailModal } from '@hs-admin/components'

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 10,
  morePageOptions: true
}

const LogOperationType = {
  OrderCreated: '创建订单',
  OrderUpdated: '更新订单',
  OrderSubmitted: '订单提交',
  OrderPaused: '停止订单',
  OrderDeleted: '删除订单',
  OrderItemCreated: '变更子订单',
  OrderItemUpdated: '更新子订单',
  OrderItemPaused: '停止子订单',
  OrderItemDeleted: '删除子订单'
}

const subItemStatus = {
  wait_for_submit: <span className="text-yellow-3">等待提交</span>,
  processing: <span className="text-orange">处理中</span>,
  stopped: <span className="text-red-6">停止</span>,
  effective: <span className="text-green">已生效</span>
}

const OrderDetail = () => {
  const paramsId = useRef<string | null>(null)

  const dataProductId = useRef('')

  const [baseInfo, setBaseInfo] = useState<any>({})

  const activeItemId = useRef('')

  const refItemModal = useRef<any>(null)

  const [itemList, setItemList] = useState<
    Array<{
      src_tb_name: string
      id: string
      code: string
      interval: 'daily' | 'weekly' | 'monthly' | 'once' | null
      sync_mode: 'whole' | 'time_offset' | null
      dst_tb_name: string | null
      column_mappings: Array<{
        src_col_name: string
        src_col_comment: string
        src_col_description: string
        dst_col_name: string
        is_required: boolean
      }>
    }>
  >([])

  const [activeItem, setActiveItem] = useState({
    specifications: [],
    spec_vals: []
  })

  const [keywords, setKeywords] = useState('')

  const [logItems, setLogItems] = useState([])

  const searchWord = useRef('')

  const refDataBaseInfo = useRef<any>()

  const theItemIsForShow = useRef(false)

  const getItems = useCallback(
    async (page: number, pageSize: number) => {
      if (paramsId.current) {
        const res = await getShoppingOrderItems(paramsId.current, {
          page_size: pageSize,
          page: page,
          keywords: keywords || undefined
        })
        setItemList(res.items)
        return res.total
      }
    },
    [keywords]
  )

  const { pagination, resetPageAndTriggerRequest, handleChange } = usePageChange(initPage, getItems)

  const doOpenDetail = async (row: any, forShowOnly = false) => {
    theItemIsForShow.current = forShowOnly

    let spec_vals = []
    let specifications = []
    let timeItems = []
    let polymerizeItems = []
    let timeID = null
    let polymerizeID = null

    if (row.data_product) {
      dataProductId.current = row.data_product.id
      const res1 = await getSpecs(row.data_product.id)
      specifications = res1.items
      const res2 = await getSpecVals({
        order_item_id: row.id
      })
      spec_vals = res2.items
      timeItems = specifications.filter((spec) => spec.type === 'time')
      polymerizeItems = specifications.filter((spec) => spec.type === 'polymerize')

      setActiveItem({
        spec_vals,
        specifications
      })
      const timeArr = spec_vals.filter((it) => it.type === 'time')
      if (timeArr.length) {
        timeID = {}
        timeArr.forEach((it) => {
          timeID[it.specification_id] = it.id
        })
      }
      const polymerizeArr = spec_vals.filter((it) => it.type === 'polymerize')
      if (polymerizeArr.length) {
        polymerizeID = {}
        timeArr.forEach((it) => {
          polymerizeID[it.specification_id] = it.id
        })
      }
    } else {
      setActiveItem({
        spec_vals,
        specifications
      })
    }

    activeItemId.current = row.id

    localShoppingData(row.id, {
      dst_tb_name: row.dst_tb_name ?? null,
      fieldList: row.column_mappings ?? [],
      sync_mode: row.sync_mode ?? null,
      interval: row.interval ?? baseInfo?.delivery?.interval,
      industryID: spec_vals.find((it) => it.type === 'industry')?.id ?? null,
      areaID: spec_vals.find((it) => it.type === 'area')?.id ?? null,
      parkID: spec_vals.find((it) => it.type === 'park')?.id ?? null,
      companyID: spec_vals.find((it) => it.type === 'company_list')?.id ?? null,
      timeID,
      polymerizeID
    })
    const areaItem = specifications.find((spec) => spec.type === 'area')
    let areaName = ''
    if (areaItem) {
      const res = await getAreaDetail(areaItem.id)
      if (!res.area_code_column) {
        if (!res.city_code_column) {
          if (res.province_code_column) {
            areaName = '省'
          }
        } else {
          areaName = '市'
        }
      } else {
        areaName = '区'
      }
    }
    refItemModal.current?.showModal(
      row.id,
      {
        industry: specifications.find((spec) => spec.type === 'industry')?.name,
        area: areaName,
        park: specifications.find((spec) => spec.type === 'park')?.name,
        company_list: specifications.find((spec) => spec.type === 'company_list')?.name,
        time: timeItems.map((it) => ({
          label: it.name,
          id: it.id
        })),
        polymerize: polymerizeItems.map((it) => ({
          label: it.name,
          id: it.id
        }))
      },
      true,
      paramsId.current,
      forShowOnly
    )
  }

  const columns = [
    {
      title: '数据项名称',
      key: 'data_product_name',
      dataIndex: 'data_product_name',
      ellipsis: true,
      className: 'text-[#328effff] hover:cursor-pointer',
      render: (name: string, row: any) => (
        <span
          className={row.data_product ? '' : 'line-through'}
          onClick={() => {
            if (!row.data_product?.id) {
              message.error('该数据项已被删除/下线')
              return
            }
            setDataItemId(row.data_product.id)
          }}>
          {name}
        </span>
      )
    },
    {
      title: '数据项表名',
      key: 'src_tb_name',
      dataIndex: 'src_tb_name'
    },
    {
      title: '目标映射表名',
      key: 'dst_tb_name',
      dataIndex: 'dst_tb_name'
    },
    {
      title: '任务周期',
      key: 'interval',
      dataIndex: 'interval',
      render: (interval: string) => getTimeLabel(interval ?? baseInfo?.delivery?.interval)
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (status: string) => subItemStatus[status] ?? '--'
    },
    {
      title: '已传输数据',
      key: 'data_count',
      dataIndex: ['task', 'total_synced'],
      render: (count: number) => count ?? '--'
    },
    {
      title: '操作',
      key: 'operation',
      dataIndex: 'operation',
      render: (_, row) => (
        <>
          <Button
            type="link"
            onClick={async () => {
              await doOpenDetail(row, true)
            }}>
            详情
          </Button>
          {row.status === 'stopped' ? (
            <Button
              type="link"
              disabled={!row.data_product}
              onClick={async () => {
                await doOpenDetail(row)
              }}>
              变更
            </Button>
          ) : (
            <Popconfirm
              title={
                row.data_product ? '订单停止后，不可直接恢复。如需恢复，通过子订单变更，重新下单。' : '该数据项已被删除，停止后将无法变更，是否继续？'
              }
              onConfirm={() => {
                pauseTheOrderItem(row.id, paramsId.current!).then(() => {
                  message.success('停止成功')
                  handleChange(pagination.current)
                  getOrderLog(paramsId.current!).then((res) => {
                    setLogItems(res.items)
                  })
                })
              }}>
              <Button type="link">停止</Button>
            </Popconfirm>
          )}
        </>
      )
    }
  ]

  const orderInfos = [
    {
      label: '订单ID',
      key: 'order_no',
      path: 'order_no'
    },
    {
      label: '订单名称',
      key: 'name',
      path: 'name'
    },
    {
      label: '需求来源',
      key: 'source',
      path: 'source'
    },
    {
      label: '关联项目名称',
      key: 'rel_project',
      path: 'proj_name'
    },
    {
      label: '查看数据环境',
      key: 'database',
      path: ['delivery', 'dst_db_conf', 'name'],
      render: (database: string) => (
        <Button
          type="link"
          onClick={() => {
            refDataBaseInfo.current?.showModal()
          }}>
          {database}
        </Button>
      )
    },
    {
      label: '提单人',
      key: 'owner',
      path: ['owner', 'name']
    },
    {
      label: '部门',
      key: 'department',
      path: ['owner', 'department', 'name']
    },
    {
      label: '提单时间',
      key: 'submit_at',
      path: 'submit_at',
      render: (time: string) => hsHandleTableDateTime(time)
    },
    {
      label: '已传输数据',
      key: 'total_synced',
      path: 'total_synced',
      render: (synced: string) => synced ?? '--'
    },
    {
      label: '状态',
      key: 'status',
      path: 'status',
      render: (state: string) => getStateLabel(state)
    }
  ]

  const [dataItemId, setDataItemId] = useState('')

  useEffect(() => {
    const id = getUrlSearchParams('id')
    paramsId.current = id

    if (id) {
      getShoppingOrderInfo(id).then((res) => {
        setBaseInfo(res)
        getProjectInfor({
          id: res.proj_id
        }).then((res2) => {
          res.proj_name = res2.name
          setBaseInfo({
            ...res
          })
        })
      })
      getOrderLog(id).then((res) => {
        setLogItems(res.items)
      })
    }
  }, [])

  useEffect(() => {
    resetPageAndTriggerRequest()
  }, [resetPageAndTriggerRequest])

  return (
    <div className="shopping-cart-wrapper">
      <div className="head-filter-part">
        <div className="common-title-style">
          <div className="shop-title">订单信息</div>
        </div>
        <div className="grid grid-cols-3 gap-2">
          {orderInfos.map((item) => (
            <div className="flex items-center" key={item.key}>
              <span className="w-7em text-lg">{item.label}</span>
              <span>
                {item.render
                  ? item.render(Array.isArray(item.path) ? item.path.reduce((acc, current) => acc?.[current], baseInfo) : baseInfo[item.path])
                  : Array.isArray(item.path)
                    ? item.path.reduce((acc, current) => acc?.[current], baseInfo)
                    : baseInfo[item.path]}
              </span>
            </div>
          ))}
        </div>
      </div>
      <div className="content-part">
        <div className="common-title-style">
          <div className="shop-title">子订单情况</div>
        </div>
        <div className="grid w-60% grid-cols-[5fr_3fr] gap-8 mb-10">
          <div className="flex items-center gap-2">
            <Input
              {...commonInputProps()}
              placeholder="请输入数据项名称、表名"
              onChange={(e) => {
                searchWord.current = e.target.value
              }}
            />
            <Button
              type="primary"
              onClick={() => {
                setKeywords(searchWord.current)
              }}>
              搜索
            </Button>
          </div>
        </div>
        <Table columns={columns} rowKey="id" dataSource={itemList} pagination={pagination} />
      </div>
      <div className="common-title-style">
        <div className="shop-title">操作记录</div>
      </div>
      <Timeline
        items={logItems.map((it) => ({
          children: (
            <>
              <p className="flex gap-4">
                <span>{it.extra_data?.operator_name ?? '--'}</span>
                <span>{LogOperationType[it.event_type]}</span>
                <span>{hsHandleTableDateTime(it.created_at)}</span>
              </p>
              {it.extra_data?.order_item_code && (
                <p className="flex gap-4">
                  <span>子订单编号：{it.extra_data?.order_item_code ?? '--'}</span>
                  <span>相关数据项：{it.extra_data?.order_item_related_table_name ?? '--'}</span>
                </p>
              )}
            </>
          )
        }))}
      />
      <DataBaseInfoModal
        ref={refDataBaseInfo}
        values={baseInfo?.delivery?.dst_db_conf ?? {}}
        onOk={async () => {
          return true
        }}
        forShow={true}
      />
      <ItemModal
        ref={refItemModal}
        onOk={async () => {
          if (theItemIsForShow.current) return
          try {
            const localData = localShoppingData(activeItemId.current)
            const ids1 = (localData['timeID'] && Object.values(localData['timeID'])) ?? []
            const ids2 = (localData['polymerizeID'] && Object.values(localData['polymerizeID'])) ?? []
            const ids3 = [localData['industryID'], localData['areaID'], localData['parkID'], localData['companyID']].filter((it) => it)
            const ids = [...ids1, ...ids2, ...ids3]

            await createOrderItem({
              spec_val_ids: ids,
              data_product_id: dataProductId.current,
              sync_mode: localData['sync_mode'],
              column_mappings: localData['fieldList'],
              interval: localData['interval'],
              dst_tb_name: localData['dst_tb_name'],
              order_id: paramsId.current!
            })
            message.success('保存成功')
            resetPageAndTriggerRequest()
            getOrderLog(paramsId.current!).then((res) => {
              setLogItems(res.items)
            })
            return true
          } catch (e) {
            console.log(e)
            return false
          }
        }}
        isLocal={true}
        cartItemInfo={activeItem}
      />
      <HsAdminDataItemDetailModal id={dataItemId} onCancel={() => setDataItemId('')} />
    </div>
  )
}

export default OrderDetail
